package gossip;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class GossipNode {

    public static void main(String[] args) {
        int port = 9000;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        GossipNode node = new GossipNode(port);
        node.start();

        // 添加种子节点
        if (port != 9000) {
            node.joinCluster(new InetSocketAddress("localhost", 9000));
        }
    }

    private final int port;
    private final GossipCore gossipCore;
    private final GossipTransport transport;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

    public GossipNode(int port) {
        this.port = port;
        this.gossipCore = new GossipCore(port);
        this.transport = new GossipTransport(port, gossipCore);
    }

    public void start() {
        transport.start();
        gossipCore.start(scheduler);
        System.out.println("Gossip node started on port " + port);
    }

    public void joinCluster(InetSocketAddress seedNode) {
        gossipCore.join(seedNode);
    }

    public void updateMetadata(String key, String value) {
        gossipCore.updateLocalMetadata(key, value);
    }

    public Map<String, MemberState> getClusterMembers() {
        return gossipCore.getMembershipTable().getMembers();
    }

}
